<!--
 * @Author: wangming
 * @Date: 2021-05-12 16:36:21
 * @LastEditors: wangming
 * @LastEditTime: 2021-10-18 15:56:42
 * @Description: file content
-->
<template>
  <el-dialog :visible="showVisible" top="5vh" :show-close="false" width="800px">
    <div class="b g3 f16 tl" slot="title">
      <div class="ks-row-between pl15 pr15">
        <span>{{ title || "自定义渲染函数" }}</span>
        <span class="el-icon-close g9 f26 poi" @click="close"></span>
      </div>
    </div>
    <div class="pl10 pr10 rel">
      <div id="tbmonaco" style="height: 540px"></div>
    </div>
    <div slot="footer" class="tr">
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" @click="submit">确 定</el-button>
    </div>
  </el-dialog>
</template>


<script>
import * as monaco from 'monaco-editor/esm/vs/editor/editor.api.js'
export default {
  data() {
    return {
      showVisible: false,
      monacojs: null,
      jsData: ``,
      title: "",
    };
  },
  methods: {
    async showjs() {
      await this.$nextTick();
      this.monacojs = monaco.editor.create(
        document.getElementById("tbmonaco"),
        {
          value: this.jsData,
          language: "javascript",
        }
      );
    },
    async showEdit(js, { title } = {}) {
      this.title = title;
      if (!!js) {
        this.jsData = js;
      }
      this.showjs();
      this.showVisible = true;
      return {
        then: (callback) => {
          if (typeof callback === "function") {
            this.callback = callback;
          }
        },
      };
    },
    close() {
      this.showVisible = false;
      if (!!this.monacojs) {
        this.monacojs.dispose();
        this.monacojs = null;
      }
    },
    submit() {
      //过滤6133函数中参数未使用报错
      let error = monaco.editor
        .getModelMarkers()
        .filter((i) => i.code !== "6133" && i.code !== "2339");
      if (error.length > 0) {
        this.$message.error("语法错误" + error[0]?.message);
        return;
      }
      this.showVisible = false;
      if (!!this.monacojs) {
        this.jsData = this.monacojs.getValue() + "";
        this.monacojs.dispose();
        this.monacojs = null;
      }
      this.callback(this.jsData);
    },
  },
};
</script>

<style lang="scss" scoped>
.closed {
  position: absolute;
  right: 5px;
  top: 5px;
  z-index: 999;
}
</style>
